<template>
  <div class="article-page">
    <!-- 页面头部 -->
    <section class="page-header bg-white dark:bg-gray-800 shadow-sm">
      <div class="container mx-auto px-4 py-6">
        <Breadcrumb
          :items="[
            { path: '/community', title: '社区' },
            { path: '/community-articles', title: '文章列表' },
            { path: '', title: article.title || '文章详情' },
          ]"
        />
      </div>
    </section>

    <!-- 文章头部 -->
    <section class="article-header bg-white dark:bg-gray-800 shadow-sm">
      <div class="container mx-auto px-4 py-8">
        <div class="max-w-4xl mx-auto">
          <!-- 文章标题 -->
          <h1 class="text-3xl font-bold mb-4">{{ article.title }}</h1>

          <!-- 文章元信息 -->
          <div class="flex items-center justify-between mb-6">
            <div class="flex items-center gap-4">
              <!-- 作者信息 -->
              <div
                class="flex items-center cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700 p-2 rounded-lg transition-colors duration-300"
                @click="handleAuthorClick"
              >
                <el-avatar :size="48" :src="article.author?.avatar" />
                <div class="ml-3">
                  <div class="font-medium">{{ article.author?.nickname }}</div>
                  <div class="text-sm text-gray-500 flex items-center gap-2">
                    <span>{{ formatTime(article.createTime) }}</span>
                    <el-tag
                      size="small"
                      type="info"
                      v-if="article.author?.isVerified"
                      >认证作者</el-tag
                    >
                  </div>
                </div>
              </div>

              <!-- 分隔符 -->
              <el-divider direction="vertical" />

              <!-- 统计信息 -->
              <div class="flex items-center gap-4 text-gray-500">
                <el-tooltip content="阅读量" placement="top">
                  <span class="flex items-center gap-1">
                    <el-icon><View /></el-icon>
                    {{ article.viewCount }}
                  </span>
                </el-tooltip>
                <el-tooltip content="收藏数" placement="top">
                  <span class="flex items-center gap-1">
                    <el-icon><Star /></el-icon>
                    {{ article.favoriteCount }}
                  </span>
                </el-tooltip>
                <el-tooltip content="评论数" placement="top">
                  <span class="flex items-center gap-1">
                    <el-icon><ChatDotRound /></el-icon>
                    {{ article.commentCount }}
                  </span>
                </el-tooltip>
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="flex items-center gap-3">
              <el-button @click="handleShare">
                <el-icon><Share /></el-icon>
                分享
              </el-button>
              <el-button
                :type="article.isFavorited ? 'warning' : 'default'"
                @click="handleFavorite"
              >
                <el-icon><Star /></el-icon>
                {{ article.isFavorited ? "已收藏" : "收藏" }}
              </el-button>
              <el-dropdown trigger="click" @command="handleMoreAction">
                <el-button>
                  <el-icon><More /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="report">举报</el-dropdown-item>
                    <el-dropdown-item command="follow"
                      >关注作者</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>

          <!-- 封面图 -->
          <div v-if="article.coverImage" class="cover-image mb-8">
            <el-image
              :src="article.coverImage"
              fit="cover"
              class="w-full rounded-lg shadow-lg hover:shadow-xl transition-shadow duration-300"
              :preview-src-list="[article.coverImage]"
            />
          </div>
        </div>
      </div>
    </section>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <div class="max-w-4xl mx-auto">
        <!-- 文章内容 -->
        <div
          class="article-content bg-white dark:bg-gray-800 rounded-lg p-8 mb-8 shadow-sm hover:shadow-md transition-shadow duration-300"
        >
          <div
            class="prose prose-lg dark:prose-invert max-w-none"
            v-html="article.content"
          ></div>

          <!-- 话题标签 -->
          <div
            v-if="article.topics?.length"
            class="topics-list mt-8 pt-8 border-t border-gray-200 dark:border-gray-700"
          >
            <div class="text-gray-500 mb-3 flex items-center">
              <el-icon class="mr-2"><Collection /></el-icon>
              相关话题：
            </div>
            <div class="flex flex-wrap gap-2">
              <el-tag
                v-for="topic in article.topics"
                :key="topic.id"
                class="cursor-pointer hover:scale-105 transition-transform duration-300"
                @click="handleTopicClick(topic)"
              >
                #{{ topic.name }}
              </el-tag>
            </div>
          </div>

          <!-- 文章底部信息 -->
          <div
            class="article-footer mt-8 pt-8 border-t border-gray-200 dark:border-gray-700"
          >
            <div class="flex items-center justify-between">
              <div class="text-sm text-gray-500">
                发布于 {{ formatDate(article.createTime) }}
                <span v-if="article.updateTime" class="ml-2">
                  · 更新于 {{ formatDate(article.updateTime) }}
                </span>
              </div>
              <div class="flex items-center gap-2">
                <el-button type="primary" link @click="handleLike">
                  <el-icon><ThumbsUp /></el-icon>
                  点赞 {{ article.likes }}
                </el-button>
                <el-button type="primary" link @click="handleShare">
                  <el-icon><Share /></el-icon>
                  分享
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 评论区 -->
        <div
          class="comments-section bg-white dark:bg-gray-800 rounded-lg p-8 shadow-sm hover:shadow-md transition-shadow duration-300"
        >
          <h2 class="text-xl font-bold mb-6 flex items-center">
            <el-icon class="mr-2"><ChatDotRound /></el-icon>
            评论 ({{ article.commentCount }})
          </h2>

          <!-- 评论输入框 -->
          <div class="comment-form mb-8">
            <el-input
              v-model="commentContent"
              type="textarea"
              :rows="3"
              :placeholder="replyTarget ? `回复 ${replyTarget.author.nickname}` : '写下你的评论...'"
              class="mb-4"
            />
            <!-- 显示已上传图片 -->
            <div v-if="commentImages.length > 0" class="uploaded-images mb-4 flex flex-wrap gap-2">
              <div v-for="(img, index) in commentImages" :key="index" class="relative">
                <el-image
                  :src="img"
                  class="w-20 h-20 rounded-lg object-cover"
                  :preview-src-list="[img]"
                />
                <el-button
                  type="danger"
                  circle
                  size="small"
                  class="absolute -top-2 -right-2"
                  @click="commentImages.splice(index, 1)"
                >
                  <el-icon><Close /></el-icon>
                </el-button>
              </div>
            </div>
            <div class="flex justify-between items-center">
              <div class="flex items-center gap-2">
                <el-upload
                  action="#"
                  :show-file-list="false"
                  :before-upload="handleImageUpload"
                  accept="image/*"
                  :disabled="commentImages.length >= 3"
                >
                  <el-button :disabled="commentImages.length >= 3">
                    <el-icon><Picture /></el-icon>
                    {{ commentImages.length >= 3 ? '最多3张图片' : '添加图片' }}
                  </el-button>
                </el-upload>
                <el-popover placement="bottom" :width="300" trigger="click">
                  <template #reference>
                    <el-button>
                      <el-icon><Emoji /></el-icon>
                      表情
                    </el-button>
                  </template>
                  <div class="emoji-picker">
                    <!-- 表情选择器内容 -->
                  </div>
                </el-popover>
                <div v-if="replyTarget">
                  <el-tag closable @close="replyTarget = null">
                    回复: {{ replyTarget.author.nickname }}
                  </el-tag>
                </div>
              </div>
              <el-button type="primary" @click="handleCommentSubmit" :loading="commentSubmitting">
                发表评论
              </el-button>
            </div>
          </div>

          <!-- 评论列表 -->
          <div class="comments-list space-y-6" v-loading="commentLoading">
            <div
              v-for="comment in comments"
              :key="comment.id"
              class="comment-item"
            >
              <div class="flex items-start gap-4">
                <el-avatar
                  :size="40"
                  :src="comment.author.avatar"
                  class="flex-shrink-0"
                />
                <div class="flex-1 min-w-0">
                  <div class="flex items-center justify-between mb-2">
                    <div class="flex items-center gap-2">
                      <span class="font-medium">{{
                        comment.author.nickname
                      }}</span>
                      <el-tag
                        size="small"
                        type="info"
                        v-if="comment.author.isVerified"
                        >认证用户</el-tag
                      >
                      <span class="text-sm text-gray-500">
                        {{ formatTime(comment.createTime) }}
                      </span>
                    </div>
                    <el-dropdown
                      trigger="click"
                      @command="handleCommentAction($event, comment)"
                    >
                      <el-button link>
                        <el-icon><More /></el-icon>
                      </el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item command="reply"
                            >回复</el-dropdown-item
                          >
                          <el-dropdown-item
                            v-if="comment.author.id === currentUser?.id"
                            command="delete"
                            divided
                          >
                            删除
                          </el-dropdown-item>
                          <el-dropdown-item v-else command="report" divided>
                            举报
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                  <div class="text-gray-900 dark:text-gray-100 mb-3">
                    {{ comment.content }}
                  </div>
                  <!-- 评论图片 -->
                  <div
                    v-if="comment.images?.length"
                    class="comment-images mb-3 flex gap-2"
                  >
                    <el-image
                      v-for="(image, index) in comment.images"
                      :key="index"
                      :src="image"
                      :preview-src-list="comment.images"
                      class="w-20 h-20 rounded-lg object-cover cursor-pointer"
                    />
                  </div>
                  <div class="flex items-center gap-4">
                    <el-button
                      link
                      :type="comment.isLiked ? 'primary' : 'default'"
                      @click="handleCommentLike(comment)"
                    >
                      <el-icon><ThumbsUp /></el-icon>
                      <span class="ml-1">{{ comment.likes }}</span>
                    </el-button>
                    <el-button link @click="handleCommentReply(comment)">
                      回复
                    </el-button>
                  </div>

                  <!-- 回复列表 -->
                  <div
                    v-if="comment.replies?.length"
                    class="replies-list mt-4 pl-4 border-l-2 border-gray-100 dark:border-gray-700"
                  >
                    <div
                      v-for="reply in comment.replies"
                      :key="reply.id"
                      class="reply-item py-3"
                    >
                      <div class="flex items-start gap-3">
                        <el-avatar
                          :size="32"
                          :src="reply.author.avatar"
                          class="flex-shrink-0"
                        />
                        <div class="flex-1 min-w-0">
                          <div class="flex items-center justify-between mb-1">
                            <div class="flex items-center gap-2">
                              <span class="font-medium">{{
                                reply.author.nickname
                              }}</span>
                              <el-tag
                                size="small"
                                type="info"
                                v-if="reply.author.isVerified"
                                >认证用户</el-tag
                              >
                              <span class="text-sm text-gray-500">
                                {{ formatTime(reply.createTime) }}
                              </span>
                            </div>
                            <el-dropdown
                              trigger="click"
                              @command="handleReplyAction($event, reply)"
                            >
                              <el-button link>
                                <el-icon><More /></el-icon>
                              </el-button>
                              <template #dropdown>
                                <el-dropdown-menu>
                                  <el-dropdown-item command="reply"
                                    >回复</el-dropdown-item
                                  >
                                  <el-dropdown-item
                                    v-if="reply.author.id === currentUser?.id"
                                    command="delete"
                                    divided
                                  >
                                    删除
                                  </el-dropdown-item>
                                  <el-dropdown-item
                                    v-else
                                    command="report"
                                    divided
                                  >
                                    举报
                                  </el-dropdown-item>
                                </el-dropdown-menu>
                              </template>
                            </el-dropdown>
                          </div>
                          <div class="text-gray-900 dark:text-gray-100">
                            {{ reply.content }}
                          </div>
                          <!-- 回复图片 -->
                          <div
                            v-if="reply.images?.length"
                            class="reply-images mt-2 flex gap-2"
                          >
                            <el-image
                              v-for="(image, index) in reply.images"
                              :key="index"
                              :src="image"
                              :preview-src-list="reply.images"
                              class="w-16 h-16 rounded-lg object-cover cursor-pointer"
                            />
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 加载更多 -->
            <div
              v-if="hasMoreComments"
              class="load-more flex justify-center pt-4"
            >
              <el-button link @click="loadMoreComments" :loading="commentLoading">
                加载更多评论
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分享弹窗 -->
    <ShareDialog
      v-model="showShareDialog"
      :title="article.title"
      :url="generateShareUrl()"
      :platforms="sharePlatforms"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  View,
  Star,
  ChatDotRound,
  Share,
  More,
  ThumbsUp,
  Picture,
  Emoji,
  Collection,
  Close,
} from "@element-plus/icons-vue";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import "dayjs/locale/zh-cn";
import ShareDialog from "@/components/global/ShareDialog.vue";
import Breadcrumb from "@/components/global/Breadcrumb.vue";
import service from "@/api/axios"; // 导入axios实例

dayjs.extend(relativeTime);
dayjs.locale("zh-cn");

const route = useRoute();
const router = useRouter();

// 文章信息
const article = ref({
  id: "",
  title: "",
  content: "",
  coverImage: "",
  author: null,
  createTime: "",
  viewCount: 0,
  favoriteCount: 0,
  commentCount: 0,
  isFavorited: false,
  topics: [],
});

// 评论相关
const commentContent = ref("");
const allComments = ref([]); // 存储所有评论
const commentPage = ref(1);
const commentPageSize = ref(10);
const hasMoreComments = computed(() => {
  return commentPage.value * commentPageSize.value < allComments.value.length;
});
const comments = computed(() => {
  const start = 0;
  const end = commentPage.value * commentPageSize.value;
  return allComments.value.slice(start, end);
});
const commentLoading = ref(false);
const commentSubmitting = ref(false);
const commentImages = ref([]); // 评论图片

// 分享相关
const showShareDialog = ref(false);
const sharePlatforms = [
  { name: "weixin", icon: "wechat", label: "微信" },
  { name: "weibo", icon: "weibo", label: "微博" },
  { name: "qq", icon: "qq", label: "QQ" },
];

// 当前用户（模拟数据）
const currentUser = ref({
  id: 1,
  nickname: "当前用户",
  avatar: "/images/avatar/default.jpg",
});

// 当前回复目标
const replyTarget = ref(null);

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).fromNow();
};

// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format("YYYY-MM-DD HH:mm");
};

// 获取文章信息
const getArticleInfo = async () => {
  try {
    // 调用API获取文章信息
    const response = await service.get(`/public/articles/${route.params.id}`);
    
    if (response && response.data) {
      Object.assign(article.value, response.data);
      // 记录浏览记录
      recordView();
    } else {
      // 使用测试数据作为后备
      Object.assign(article.value, {
        id: route.params.id,
        title: "探秘贵港古镇：一场穿越时空的文化之旅",
        content: `
          <p>走进贵港古镇，仿佛穿越时空，回到了那个充满传统韵味的年代。古镇的每一条街巷、每一座建筑都诉说着悠久的历史故事。</p>
          <p>古镇最引人注目的是那些保存完好的明清建筑，青砖黛瓦，雕梁画栋，展现着精湛的岭南建筑艺术。走在石板铺就的街道上，两旁的老店铺仍保持着传统的营业方式，售卖着地道的手工艺品和特色小吃。</p>
          <h2>建筑特色</h2>
          <p>古镇的建筑融合了岭南文化的特色，以砖木结构为主，讲究通风采光。天井的设计不仅实用，更是传统居家生活的缩影。</p>
          <h2>特色美食</h2>
          <p>古镇内有许多百年老店，传承着独特的美食文化。无论是地道的肠粉，还是传统的糕点，都能让人品味到浓浓的乡土气息。</p>
        `,
        coverImage: "/images/featured/ancient-town.jpg",
        author: {
          id: 1,
          nickname: "文化记录者",
          avatar: "/images/avatar/user1.jpg",
          isVerified: true,
        },
        createTime: "2024-03-15 10:00:00",
        updateTime: "2024-03-15 12:00:00",
        viewCount: 1234,
        favoriteCount: 56,
        commentCount: 23,
        likes: 89,
        isFavorited: false,
        topics: [
          { id: 1, name: "贵港古镇" },
          { id: 2, name: "文化探索" },
        ],
      });
    }
  } catch (error) {
    console.error("获取文章信息失败:", error);
    
    // 使用测试数据作为后备
    Object.assign(article.value, {
      id: route.params.id,
      title: "探秘贵港古镇：一场穿越时空的文化之旅",
      content: `
        <p>走进贵港古镇，仿佛穿越时空，回到了那个充满传统韵味的年代。古镇的每一条街巷、每一座建筑都诉说着悠久的历史故事。</p>
        <p>古镇最引人注目的是那些保存完好的明清建筑，青砖黛瓦，雕梁画栋，展现着精湛的岭南建筑艺术。走在石板铺就的街道上，两旁的老店铺仍保持着传统的营业方式，售卖着地道的手工艺品和特色小吃。</p>
        <h2>建筑特色</h2>
        <p>古镇的建筑融合了岭南文化的特色，以砖木结构为主，讲究通风采光。天井的设计不仅实用，更是传统居家生活的缩影。</p>
        <h2>特色美食</h2>
        <p>古镇内有许多百年老店，传承着独特的美食文化。无论是地道的肠粉，还是传统的糕点，都能让人品味到浓浓的乡土气息。</p>
      `,
      coverImage: "/images/featured/ancient-town.jpg",
      author: {
        id: 1,
        nickname: "文化记录者",
        avatar: "/images/avatar/user1.jpg",
        isVerified: true,
      },
      createTime: "2024-03-15 10:00:00",
      updateTime: "2024-03-15 12:00:00",
      viewCount: 1234,
      favoriteCount: 56,
      commentCount: 23,
      likes: 89,
      isFavorited: false,
      topics: [
        { id: 1, name: "贵港古镇" },
        { id: 2, name: "文化探索" },
      ],
    });
  }
};

// 记录浏览记录
const recordView = async () => {
  try {
    await service.post(`/articles/view/${article.value.id}`);
  } catch (error) {
    console.error("记录浏览失败:", error);
  }
};

// 获取评论列表
const getComments = async () => {
  if (commentLoading.value) return;
  
  commentLoading.value = true;
  try {
    // 调用API获取所有评论
    const response = await service.get(`/public/articles/${route.params.id}/comments`);
    
    if (response && response.data && Array.isArray(response.data)) {
      allComments.value = response.data;
    } else {
      // 使用测试数据作为后备
      allComments.value = [
        {
          id: 1,
          content: "古镇的建筑真的很有特色，值得一去！",
          author: {
            id: 2,
            nickname: "旅行达人",
            avatar: "/images/avatar/user2.jpg",
          },
          createTime: "2024-03-15 11:00:00",
          likes: 12,
          isLiked: false,
          replies: [
            {
              id: 11,
              content: "同意，建议周末去，人少一些",
              author: {
                id: 3,
                nickname: "本地通",
                avatar: "/images/avatar/user3.jpg",
              },
              createTime: "2024-03-15 11:30:00",
            },
          ],
        },
        {
          id: 2,
          content: "我上周刚去过，真的很美，特别是那些老建筑，保存得非常好！",
          author: {
            id: 4,
            nickname: "历史爱好者",
            avatar: "/images/avatar/user4.jpg",
          },
          createTime: "2024-03-14 16:45:00",
          likes: 8,
          isLiked: false,
          replies: [],
        },
        {
          id: 3,
          content: "美食也很赞，尤其是古镇上的那家老字号肠粉店，必须试试！",
          author: {
            id: 5,
            nickname: "吃货小王",
            avatar: "/images/avatar/user5.jpg",
          },
          createTime: "2024-03-13 09:20:00",
          likes: 15,
          isLiked: true,
          replies: [],
        },
      ];
    }
  } catch (error) {
    console.error("获取评论列表失败:", error);
    
    // 使用测试数据作为后备
    allComments.value = [
      {
        id: 1,
        content: "古镇的建筑真的很有特色，值得一去！",
        author: {
          id: 2,
          nickname: "旅行达人",
          avatar: "/images/avatar/user2.jpg",
        },
        createTime: "2024-03-15 11:00:00",
        likes: 12,
        isLiked: false,
        replies: [
          {
            id: 11,
            content: "同意，建议周末去，人少一些",
            author: {
              id: 3,
              nickname: "本地通",
              avatar: "/images/avatar/user3.jpg",
            },
            createTime: "2024-03-15 11:30:00",
          },
        ],
      },
    ];
  } finally {
    commentLoading.value = false;
  }
};

// 加载更多评论
const loadMoreComments = () => {
  if (hasMoreComments.value) {
    commentPage.value += 1;
  }
};

// 处理作者点击
const handleAuthorClick = () => {
  router.push(`/user/profile/${article.value.author.id}`);
};

// 处理话题点击
const handleTopicClick = (topic) => {
  router.push(`/community/topic/${topic.id}`);
};

// 处理分享
const handleShare = () => {
  showShareDialog.value = true;
};

// 生成分享链接
const generateShareUrl = () => {
  return `${window.location.origin}/community/article/${article.value.id}`;
};

// 处理收藏
const handleFavorite = async () => {
  try {
    let response;
    if (!article.value.isFavorited) {
      response = await service.post(`/articles/favorite/${article.value.id}`);
    } else {
      response = await service.delete(`/articles/favorite/${article.value.id}`);
    }
    
    if (response && response.data && response.data.success) {
      article.value.isFavorited = !article.value.isFavorited;
      article.value.favoriteCount += article.value.isFavorited ? 1 : -1;
      ElMessage.success(article.value.isFavorited ? "收藏成功" : "已取消收藏");
    }
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败");
  }
};

// 处理点赞
const handleLike = async () => {
  try {
    const result = await service.post(`/articles/like/${article.value.id}`);
    
    if (result && result.data && result.data.liked !== undefined) {
      article.value.isLiked = result.data.liked;
      article.value.likes += result.data.liked ? 1 : -1;
      ElMessage.success(result.data.liked ? "点赞成功" : "已取消点赞");
    } else {
      // 简单处理
      article.value.isLiked = !article.value.isLiked;
      article.value.likes += article.value.isLiked ? 1 : -1;
      ElMessage.success(article.value.isLiked ? "点赞成功" : "已取消点赞");
    }
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败");
  }
};

// 处理图片上传
const handleImageUpload = (file) => {
  // 检查文件类型和大小
  const isImage = /^image\//.test(file.type);
  const isLt2M = file.size / 1024 / 1024 < 2;
  
  if (!isImage) {
    ElMessage.error("只能上传图片文件！");
    return false;
  }
  
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过2MB！");
    return false;
  }
  
  // 创建FormData对象
  const formData = new FormData();
  formData.append("file", file);
  
  // 上传图片
  service.post("/upload/image", formData, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  }).then(response => {
    if (response && response.data && response.data.url) {
      commentImages.value.push(response.data.url);
      ElMessage.success("图片上传成功");
    } else {
      ElMessage.error("图片上传失败");
    }
  }).catch(error => {
    console.error("图片上传失败:", error);
    ElMessage.error("图片上传失败");
  });
  
  return false; // 阻止默认上传行为
};

// 处理评论提交
const handleCommentSubmit = async () => {
  if (!commentContent.value.trim() && commentImages.value.length === 0) {
    ElMessage.warning("请输入评论内容或上传图片");
    return;
  }
  
  commentSubmitting.value = true;
  try {
    // 构建评论数据
    const commentData = {
      content: commentContent.value,
      images: commentImages.value,
      parentId: replyTarget.value ? replyTarget.value.id : null,
      articleId: article.value.id,
    };
    
    // 调用API提交评论
    const response = await service.post("/articles/comment", commentData);
    
    if (response && response.data && response.data.id) {
      // 如果是回复评论
      if (replyTarget.value) {
        // 查找父评论并添加回复
        const parentComment = comments.value.find(c => c.id === (replyTarget.value.parentId || replyTarget.value.id));
        if (parentComment) {
          if (!parentComment.replies) {
            parentComment.replies = [];
          }
          
          parentComment.replies.push({
            id: response.data.id,
            content: commentContent.value,
            images: commentImages.value,
            author: currentUser.value,
            createTime: new Date().toISOString(),
          });
        }
      } else {
        // 添加新评论到列表顶部
        const newComment = {
          id: response.data.id,
          content: commentContent.value,
          images: commentImages.value,
          author: currentUser.value,
          createTime: new Date().toISOString(),
          likes: 0,
          isLiked: false,
          replies: [],
        };
        
        comments.value.unshift(newComment);
      }
      
      // 更新文章评论数
      article.value.commentCount += 1;
      
      // 重置表单
      commentContent.value = "";
      commentImages.value = [];
      replyTarget.value = null;
      
      ElMessage.success("评论成功");
    } else {
      // 使用前端模拟
      if (replyTarget.value) {
        // 查找父评论并添加回复
        const parentComment = comments.value.find(c => c.id === (replyTarget.value.parentId || replyTarget.value.id));
        if (parentComment) {
          if (!parentComment.replies) {
            parentComment.replies = [];
          }
          
          parentComment.replies.push({
            id: Date.now(),
            content: commentContent.value,
            images: commentImages.value,
            author: currentUser.value,
            createTime: new Date().toISOString(),
          });
        }
      } else {
        // 添加新评论到列表顶部
        const newComment = {
          id: Date.now(),
          content: commentContent.value,
          images: commentImages.value,
          author: currentUser.value,
          createTime: new Date().toISOString(),
          likes: 0,
          isLiked: false,
          replies: [],
        };
        
        comments.value.unshift(newComment);
      }
      
      // 更新文章评论数
      article.value.commentCount += 1;
      
      // 重置表单
      commentContent.value = "";
      commentImages.value = [];
      replyTarget.value = null;
      
      ElMessage.success("评论成功");
    }
  } catch (error) {
    console.error("评论失败:", error);
    ElMessage.error("评论失败");
  } finally {
    commentSubmitting.value = false;
  }
};

// 处理评论点赞
const handleCommentLike = async (comment) => {
  try {
    const result = await service.post(`/articles/comment/like/${comment.id}`);
    
    if (result && result.data && result.data.liked !== undefined) {
      comment.isLiked = result.data.liked;
      comment.likes += result.data.liked ? 1 : -1;
      ElMessage.success(result.data.liked ? "点赞成功" : "已取消点赞");
    } else {
      // 简单处理
      comment.isLiked = !comment.isLiked;
      comment.likes += comment.isLiked ? 1 : -1;
      ElMessage.success(comment.isLiked ? "点赞成功" : "已取消点赞");
    }
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败");
  }
};

// 处理评论回复
const handleCommentReply = (comment) => {
  replyTarget.value = comment;
  commentContent.value = `@${comment.author.nickname} `;
  // 滚动到评论框
  document.querySelector('.comment-form').scrollIntoView({ behavior: 'smooth' });
};

// 处理评论操作
const handleCommentAction = async (command, comment) => {
  switch (command) {
    case "reply":
      handleCommentReply(comment);
      break;
    case "delete":
      try {
        await ElMessageBox.confirm("确定要删除这条评论吗？", "提示", {
          type: "warning",
        });
        
        // 调用API删除评论
        await service.delete(`/articles/comment/${comment.id}`);
        
        // 从列表中移除评论
        const index = comments.value.findIndex((c) => c.id === comment.id);
        if (index > -1) {
          comments.value.splice(index, 1);
          article.value.commentCount -= 1;
        }
        
        ElMessage.success("删除成功");
      } catch (error) {
        if (error !== "cancel") {
          console.error("删除失败:", error);
          ElMessage.error("删除失败");
        }
      }
      break;
    case "report":
      ElMessage.success("举报已提交");
      break;
  }
};

// 处理回复操作
const handleReplyAction = async (command, reply) => {
  switch (command) {
    case "reply":
      // 设置回复目标，包含父评论ID
      replyTarget.value = {
        ...reply,
        parentId: comments.value.find(c => c.replies && c.replies.some(r => r.id === reply.id))?.id,
      };
      commentContent.value = `@${reply.author.nickname} `;
      // 滚动到评论框
      document.querySelector('.comment-form').scrollIntoView({ behavior: 'smooth' });
      break;
    case "delete":
      try {
        await ElMessageBox.confirm("确定要删除这条回复吗？", "提示", {
          type: "warning",
        });
        
        // 调用API删除回复
        await service.delete(`/articles/comment/${reply.id}`);
        
        // 从父评论的回复列表中移除
        for (const comment of comments.value) {
          if (comment.replies) {
            const replyIndex = comment.replies.findIndex(r => r.id === reply.id);
            if (replyIndex > -1) {
              comment.replies.splice(replyIndex, 1);
              article.value.commentCount -= 1;
              break;
            }
          }
        }
        
        ElMessage.success("删除成功");
      } catch (error) {
        if (error !== "cancel") {
          console.error("删除失败:", error);
          ElMessage.error("删除失败");
        }
      }
      break;
    case "report":
      ElMessage.success("举报已提交");
      break;
  }
};

// 处理更多操作
const handleMoreAction = (command) => {
  switch (command) {
    case "report":
      ElMessage.success("举报已提交，我们会尽快处理");
      break;
    case "follow":
      ElMessage.success("关注成功");
      break;
  }
};

// 初始化
onMounted(() => {
  getArticleInfo();
  getComments();
  
  // 加载当前用户信息
  try {
    service.get("/user/info").then(response => {
      if (response && response.data) {
        currentUser.value = response.data;
      }
    });
  } catch (error) {
    console.error("获取用户信息失败:", error);
  }
});
</script>

<style lang="scss">
.article-page {
  .article-content {
    .prose {
      h1 {
        @apply text-3xl font-bold mb-6;
      }

      h2 {
        @apply text-2xl font-bold mb-4 mt-8;
      }

      h3 {
        @apply text-xl font-bold mb-3 mt-6;
      }

      p {
        @apply mb-4 leading-relaxed;
      }

      img {
        @apply rounded-lg my-6;
      }

      ul,
      ol {
        @apply my-4 pl-6;

        li {
          @apply mb-2;
        }
      }

      blockquote {
        @apply border-l-4 border-gray-300 dark:border-gray-600 pl-4 my-4 italic;
      }
    }
  }

  .comments-section {
    .comment-item {
      @apply border-b border-gray-100 dark:border-gray-700 last:border-0 pb-6;
    }
  }
}
</style>
